/**
 * Copyright (C) 2018-2022
 * All rights reserved, Designed By www.yixiang.co
 * 注意：
 * 本软件为www.yixiang.co开发研制
 */
package co.yixiang.modules.order.order.serviceimpl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import co.yixiang.cache.Cache;
import co.yixiang.common.enums.GoodsSalesModeEnum;
import co.yixiang.common.enums.ResultCode;
import co.yixiang.common.exception.ServiceException;
import co.yixiang.common.security.UserContext;
import co.yixiang.common.service.impl.BaseServiceImpl;
import co.yixiang.common.utils.CurrencyUtil;
import co.yixiang.common.utils.FileUtil;
import co.yixiang.common.utils.QueryHelpPlus;
import co.yixiang.common.utils.SecurityUtils;
import co.yixiang.dozer.service.IGenerator;
import co.yixiang.modules.activity.entity.domain.YxStoreCouponUser;
import co.yixiang.modules.adopt.entity.domain.YxAdoptProduct;
import co.yixiang.modules.adopt.service.YxAdoptProductService;
import co.yixiang.modules.goods.entity.domain.YxStoreProduct;
import co.yixiang.modules.goods.entity.dto.YxStoreCartQueryCriteria;
import co.yixiang.modules.goods.entity.enums.GoodsStatusEnum;
import co.yixiang.modules.goods.service.YxStoreProductService;
import co.yixiang.modules.member.entity.domain.UserAddress;
import co.yixiang.modules.member.service.UserAddressService;
import co.yixiang.modules.member.service.YxUserService;
import co.yixiang.modules.order.cart.entity.dto.TradeDTO;
import co.yixiang.modules.order.cart.entity.enums.CartTypeEnum;
import co.yixiang.modules.order.cart.entity.enums.DeliveryMethodEnum;
import co.yixiang.modules.order.cart.entity.vo.CartSkuVO;
import co.yixiang.modules.order.cart.entity.vo.CartVO;
import co.yixiang.modules.order.cart.entity.vo.TradeParams;
import co.yixiang.modules.order.cart.render.TradeBuilder;
import co.yixiang.modules.order.order.entity.domain.Trade;
import co.yixiang.modules.order.order.entity.domain.YxStoreCart;
import co.yixiang.modules.order.order.entity.dto.YxStoreCartDto;
import co.yixiang.modules.order.order.service.YxStoreCartService;
import co.yixiang.modules.security.entity.vo.AuthUser;
import co.yixiang.modules.shop.entity.dto.CountDto;
import co.yixiang.modules.order.order.mapper.StoreCartMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

// 默认不使用缓存
//import org.springframework.cache.annotation.CacheConfig;
//import org.springframework.cache.annotation.CacheEvict;
//import org.springframework.cache.annotation.Cacheable;

/**
 * @author hupeng
 * @date 2020-05-12
 */
@Service
//@CacheConfig(cacheNames = "yxStoreCart")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class YxStoreCartServiceImpl extends BaseServiceImpl<StoreCartMapper, YxStoreCart> implements YxStoreCartService {

    static String errorMessage = "购物车异常，请稍后重试";

    @Autowired
    private IGenerator generator;
    /**
     * 交易
     */
    @Autowired
    private TradeBuilder tradeBuilder;
    /**
     * 缓存
     */
    @Autowired
    private Cache<Object> cache;
    /**
     * 商品
     */
    @Autowired
    private YxStoreProductService productService;

    /**
     * 认养
     */
    @Autowired
    private YxAdoptProductService adoptService;
    /**
     * 会员
     */
    @Autowired
    private YxUserService userService;
    /**
     * 会员地址
     */
    @Autowired
    private UserAddressService userAddressService;

    @Override
    //@Cacheable
    public Map<String, Object> queryAll(YxStoreCartQueryCriteria criteria, Pageable pageable) {
        getPage(pageable);
        PageInfo<YxStoreCart> page = new PageInfo<>(queryAll(criteria));
        Map<String, Object> map = new LinkedHashMap<>(2);
        map.put("content", generator.convert(page.getList(), YxStoreCartDto.class));
        map.put("totalElements", page.getTotal());
        return map;
    }


    @Override
    //@Cacheable
    public List<YxStoreCart> queryAll(YxStoreCartQueryCriteria criteria) {
        return baseMapper.selectList(QueryHelpPlus.getPredicate(YxStoreCart.class, criteria));
    }


    @Override
    public void download(List<YxStoreCartDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (YxStoreCartDto yxStoreCart : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("用户ID", yxStoreCart.getUid());
            map.put("类型", yxStoreCart.getType());
            map.put("商品ID", yxStoreCart.getProductId());
            map.put("商品属性", yxStoreCart.getProductAttrUnique());
            map.put("商品数量", yxStoreCart.getCartNum());
            map.put("0 = 未购买 1 = 已购买", yxStoreCart.getIsPay());
            map.put("是否为立即购买", yxStoreCart.getIsNew());
            map.put("拼团id", yxStoreCart.getCombinationId());
            map.put("秒杀产品ID", yxStoreCart.getSeckillId());
            map.put("砍价id", yxStoreCart.getBargainId());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public List<CountDto> findCateName() {
        return baseMapper.findCateName();
    }

    @Override
    public void initCart() {
        final AuthUser authUser = SecurityUtils.getAuthUser();
        final List<YxStoreCart> list = this.list(new LambdaQueryWrapper<YxStoreCart>().eq(YxStoreCart::getUid, authUser.getUuid()));
        if (ObjectUtil.isNotEmpty(list)) {
            Map<Long, Integer> collect = list.stream().collect(Collectors.toMap(YxStoreCart::getProductId, YxStoreCart::getCartNum));
            // 初始化 TradeDTO
            // 购物车默认类型 CART
            CartTypeEnum cartType = CartTypeEnum.CART;
            TradeDTO tradeDTO = this.readDTO(cartType);
            List<CartSkuVO> cartSkuVOS = tradeDTO.getSkuList();
            // 放入商品数据
            for (Map.Entry<Long, Integer> entry : collect.entrySet()) {
                // 获取商品
                YxStoreProduct dataGoods = checkGoods(entry.getKey().toString());
                // 创建一个vo
                CartSkuVO cartSkuVO = new CartSkuVO(dataGoods, null);
                cartSkuVO.setCartType(cartType);
                // 检查购物车数据
                this.checkSetGoodsQuantity(cartSkuVO, entry.getKey().toString(), entry.getValue());
                // 计算价格
                cartSkuVO.setSubTotal(CurrencyUtil.mul(cartSkuVO.getPurchasePrice(),cartSkuVO.getNum()));
                // 默认选中状态
                cartSkuVO.setChecked(Boolean.TRUE);
                cartSkuVOS.add(cartSkuVO);
            }
            // 缓存起来
            this.resetTradeDTO(tradeDTO);
        }
    }


    @Override
    public void add(String skuId, Integer num, String cartType, Boolean cover) {
        // 获取当前登录的用户（会员）
        // AuthUser currentUser = Objects.requireNonNull(UserContext.getCurrentUser());
        final AuthUser authUser = SecurityUtils.getAuthUser();
        if (num <= 0) {
            throw new ServiceException(ResultCode.CART_NUM_ERROR);
        }
        CartTypeEnum cartTypeEnum = getCartType(cartType);
        YxStoreProduct dataProduct = new YxStoreProduct();
        if (cartTypeEnum.equals(CartTypeEnum.ADOPT)) {
            YxAdoptProduct yxAdoptProduct = checkAdopt(skuId);
            BeanUtil.copyProperties(yxAdoptProduct, dataProduct);
            dataProduct.setStoreName(yxAdoptProduct.getAdoptName());
        } else {
            dataProduct = checkGoods(skuId);
        }

        try {
            //购物车方式购买需要保存之前的选择，其他方式购买，则直接抹除掉之前的记录
            TradeDTO tradeDTO;
            // 保存到DB
            YxStoreCart cart = new YxStoreCart();
            if (cartTypeEnum.equals(CartTypeEnum.CART)) {
                //如果存在，则变更数量不做新增，否则新增一个商品进入集合
                tradeDTO = this.readDTO(cartTypeEnum);
                List<CartSkuVO> cartSkuVOS = tradeDTO.getSkuList();
                CartSkuVO cartSkuVO = cartSkuVOS.stream().filter(i -> i.getGoodsSku().getId().equals(Long.parseLong(skuId))).findFirst().orElse(null);
                //购物车中已经存在，更新数量
                if (cartSkuVO != null && dataProduct.getCreateTime().equals(cartSkuVO.getGoodsSku().getCreateTime())) {
                    //如果覆盖购物车中商品数量
                    if (Boolean.TRUE.equals(cover)) {
                        cartSkuVO.setNum(num);
                        this.checkSetGoodsQuantity(cartSkuVO, skuId, num);
                    } else {
                        int oldNum = cartSkuVO.getNum();
                        int newNum = oldNum + num;
                        this.checkSetGoodsQuantity(cartSkuVO, skuId, newNum);
                    }
                    cart = this.getOne(new LambdaQueryWrapper<YxStoreCart>().eq(YxStoreCart::getUid, tradeDTO.getUid()).eq(YxStoreCart::getProductId, skuId));
                    if  (ObjectUtil.isNotEmpty(cart)) {
                        cart.setCartNum(num + cart.getCartNum());
                    }
                    //计算购物车小计
                    cartSkuVO.setSubTotal(CurrencyUtil.mul(cartSkuVO.getPurchasePrice(), cartSkuVO.getNum()));
                } else {
                    //先清理一下 如果商品无效的话
                    cartSkuVOS.remove(cartSkuVO);
                    //购物车中不存在此商品，则新建立一个
                    cartSkuVO = new CartSkuVO(dataProduct, null);
                    cartSkuVO.setCartType(cartTypeEnum);
                    //再设置加入购物车的数量
                    this.checkSetGoodsQuantity(cartSkuVO, skuId, num);
                    //计算购物车小计
                    cartSkuVO.setSubTotal(CurrencyUtil.mul(cartSkuVO.getPurchasePrice(), cartSkuVO.getNum()));
                    cartSkuVOS.add(cartSkuVO);
                    cart = new YxStoreCart(tradeDTO);
                    cart.setCartNum(cartSkuVO.getNum());
                    cart.setProductId(cartSkuVO.getGoodsSku().getId());
                    cart.setProductAttrUnique("");
                    cart.setType("product");
                }
                //新加入的商品都是选中的
                cartSkuVO.setChecked(true);
            }
            else if (cartTypeEnum.equals(CartTypeEnum.ADOPT)) {
                tradeDTO = new TradeDTO(cartTypeEnum);
                tradeDTO.setUid(authUser.getUuid());
                tradeDTO.setRealName(authUser.getRealName());
                List<CartSkuVO> cartSkuVOS = tradeDTO.getSkuList();
                //购物车中不存在此商品，则新建立一个
                CartSkuVO cartSkuVO = new CartSkuVO(dataProduct, null);
                cartSkuVO.setCartType(cartTypeEnum);
                //检测购物车数据
                checkCart(cartTypeEnum, cartSkuVO, skuId, num);
                //计算购物车小计
                cartSkuVO.setSubTotal(CurrencyUtil.mul(cartSkuVO.getPurchasePrice(), cartSkuVO.getNum()));
                cartSkuVOS.add(cartSkuVO);
            }
            else {
                tradeDTO = new TradeDTO(cartTypeEnum);
                tradeDTO.setUid(authUser.getUuid());
                tradeDTO.setRealName(authUser.getRealName());
                List<CartSkuVO> cartSkuVOS = tradeDTO.getSkuList();
                //购物车中不存在此商品，则新建立一个
                CartSkuVO cartSkuVO = new CartSkuVO(dataProduct, null);
                cartSkuVO.setCartType(cartTypeEnum);
                //检测购物车数据
                checkCart(cartTypeEnum, cartSkuVO, skuId, num);
                //计算购物车小计
                cartSkuVO.setSubTotal(CurrencyUtil.mul(cartSkuVO.getPurchasePrice(), cartSkuVO.getNum()));
                cartSkuVOS.add(cartSkuVO);
            }
            tradeDTO.setCartTypeEnum(cartTypeEnum);
            remoteCoupon(tradeDTO);
            // 缓存起来
            // 修改数据库DB
            if  (ObjectUtil.isNotEmpty(cart) && ObjectUtil.isNotEmpty(cart.getUid())){
                this.saveOrUpdate(cart);
            }
            this.resetTradeDTO(tradeDTO);
        } catch (ServiceException serviceException) {
            throw serviceException;
        } catch (Exception e) {
            log.error("购物车渲染异常", e);
            throw new ServiceException(errorMessage);
        }
    }

    /**
     * 读取当前会员购物原始数据key
     *
     * @param cartTypeEnum 获取方式
     * @return 当前会员购物原始数据key
     */
    private String getOriginKey(CartTypeEnum cartTypeEnum) {

        //缓存key，默认使用购物车
        if (cartTypeEnum != null) {
            final AuthUser authUser = SecurityUtils.getAuthUser();
            return cartTypeEnum.getPrefix() + authUser.getUuid();
        }
        throw new ServiceException(ResultCode.ERROR);
    }

    @Override
    public TradeDTO readDTO(CartTypeEnum checkedWay) {
        //TradeDTO tradeDTO = new Gson().fromJson(cache.getFormJson(this.getOriginKey(checkedWay)),TradeDTO.class);
        TradeDTO tradeDTO = cache.getRetrunObject(this.getOriginKey(checkedWay),TradeDTO.class);
        if (tradeDTO == null) {
            tradeDTO = new TradeDTO(checkedWay);
            AuthUser authUser = SecurityUtils.getAuthUser();
            tradeDTO.setUid(authUser.getUuid());
            tradeDTO.setRealName(authUser.getRealName());
        }
        if (tradeDTO.getUserAddress()== null) {
            tradeDTO.setUserAddress(this.userAddressService.getDefaultAddress());
        }
        return tradeDTO;
    }

    @Override
    public void checked(String skuId, boolean checked) {
        TradeDTO tradeDTO = this.readDTO(CartTypeEnum.CART);

        remoteCoupon(tradeDTO);

        List<CartSkuVO> cartSkuVOS = tradeDTO.getSkuList();
        for (CartSkuVO cartSkuVO : cartSkuVOS) {
            if (cartSkuVO.getGoodsSku().getId().equals(Long.parseLong(skuId))) {
                cartSkuVO.setChecked(checked);
            }
        }

        this.resetTradeDTO(tradeDTO);
    }

    @Override
    public void checkedStore(String storeId, boolean checked) {
        TradeDTO tradeDTO = this.readDTO(CartTypeEnum.CART);

        remoteCoupon(tradeDTO);

        List<CartSkuVO> cartSkuVOS = tradeDTO.getSkuList();
        for (CartSkuVO cartSkuVO : cartSkuVOS) {
//            if (cartSkuVO.getStoreId().equals(storeId)) {
//
//            }
            cartSkuVO.setChecked(checked);
        }

        resetTradeDTO(tradeDTO);
    }

    @Override
    public void checkedAll(boolean checked) {
        TradeDTO tradeDTO = this.readDTO(CartTypeEnum.CART);

        remoteCoupon(tradeDTO);

        List<CartSkuVO> cartSkuVOS = tradeDTO.getSkuList();
        for (CartSkuVO cartSkuVO : cartSkuVOS) {
            cartSkuVO.setChecked(checked);
        }
        resetTradeDTO(tradeDTO);
    }

    /**
     * 当购物车商品发生变更时，取消已选择当优惠券
     *
     * @param tradeDTO
     */
    private void remoteCoupon(TradeDTO tradeDTO) {

        // tradeDTO.setPlatformCoupon(null);
    }

    @Override
    public void delete(String[] skuIds) {
        TradeDTO tradeDTO = this.readDTO(CartTypeEnum.CART);
        List<CartSkuVO> cartSkuVOS = tradeDTO.getSkuList();
        List<CartSkuVO> deleteVos = new ArrayList<>();
        List<Long> goodsId = new ArrayList<>();
        for (CartSkuVO cartSkuVO : cartSkuVOS) {
            for (String skuId : skuIds) {
                if (cartSkuVO.getGoodsSku().getId().equals(Long.parseLong(skuId))) {
                    deleteVos.add(cartSkuVO);
                    goodsId.add(cartSkuVO.getGoodsSku().getId());
                }
            }
        }
        // 删除购物车
        cartSkuVOS.removeAll(deleteVos);
        this.remove(new LambdaQueryWrapper<YxStoreCart>().eq(YxStoreCart::getUid,tradeDTO.getUid()).in(YxStoreCart::getProductId,goodsId));
        resetTradeDTO(tradeDTO);
    }

    @Override
    public void clean() {
        final AuthUser authUser = SecurityUtils.getAuthUser();
        cache.remove(this.getOriginKey(CartTypeEnum.CART));
        this.remove(new LambdaQueryWrapper<YxStoreCart>().eq(YxStoreCart::getUid,authUser.getUuid()));
    }

    public void cleanChecked(TradeDTO tradeDTO) {
        List<CartSkuVO> cartSkuVOS = tradeDTO.getSkuList();
        List<CartSkuVO> deleteVos = new ArrayList<>();
        for (CartSkuVO cartSkuVO : cartSkuVOS) {
            if (Boolean.TRUE.equals(cartSkuVO.getChecked())) {
                deleteVos.add(cartSkuVO);
            }
        }
        cartSkuVOS.removeAll(deleteVos);
        //清除选择的优惠券
        // tradeDTO.setPlatformCoupon(null);

        resetTradeDTO(tradeDTO);
    }

    @Override
    public void resetTradeDTO(TradeDTO tradeDTO) {
        cache.put(this.getOriginKey(tradeDTO.getCartTypeEnum()), tradeDTO);
    }

    @Override
    public TradeDTO getCheckedTradeDTO(CartTypeEnum way) {
        return tradeBuilder.buildChecked(way);
    }

    /**
     * 获取可使用的优惠券数量
     *
     * @param checkedWay 购物车购买：CART/立即购买：BUY_NOW/拼团购买：PINTUAN / 积分购买：POINT
     * @return 可使用的优惠券数量
     */
    @Override
    public Long getCanUseCoupon(CartTypeEnum checkedWay) {
        TradeDTO tradeDTO = this.readDTO(checkedWay);
        long count = 0L;
        double totalPrice = tradeDTO.getSkuList().stream().mapToDouble(i -> i.getPurchasePrice() * i.getNum()).sum();
        if (tradeDTO.getSkuList() != null && !tradeDTO.getSkuList().isEmpty()) {
            List<String> ids = tradeDTO.getSkuList().stream().filter(i -> Boolean.TRUE.equals(i.getChecked())).map(i -> i.getGoodsSku().getId().toString()).collect(Collectors.toList());

            // List<EsGoodsIndex> esGoodsList = esGoodsSearchService.getEsGoodsBySkuIds(ids, null);
            List<String> storeIds = new ArrayList<>();

            //获取可操作的优惠券集合
//            List<MemberCoupon> allScopeMemberCoupon = memberCouponService.getAllScopeMemberCoupon(tradeDTO.getMemberId(), storeIds);
//            if (allScopeMemberCoupon != null && !allScopeMemberCoupon.isEmpty()) {
//                //过滤满足消费门槛
//                count += allScopeMemberCoupon.stream().filter(i -> i.getConsumeThreshold() <= totalPrice).count();
//            }
        }
        return count;
    }

    @Override
    public TradeDTO getAllTradeDTO() {
        return tradeBuilder.buildCart(CartTypeEnum.CART);
    }

    /**
     * 校验商品有效性，判定失效和库存，促销活动价格
     *
     * @param skuId 商品skuId
     */
    private YxStoreProduct checkGoods(String skuId) {
        YxStoreProduct data = this.productService.getGoodsByIdFromCache(Long.parseLong(skuId));
        if (data == null) {
            throw new ServiceException(ResultCode.GOODS_NOT_EXIST);
        }
        if (!GoodsStatusEnum.UPPER.status().equals(data.getIsShow())) {
            throw new ServiceException(ResultCode.GOODS_NOT_EXIST);
        }
        return data;
    }

    /**
     * 校验认养商品有效性，判定失效和库存
     *
     * @param skuId 商品skuId
     */
    private YxAdoptProduct checkAdopt(String skuId) {
        YxAdoptProduct data = this.adoptService.getGoodsByIdFromCache(Long.parseLong(skuId));
        if (data == null) {
            throw new ServiceException(ResultCode.GOODS_NOT_EXIST);
        }
        if (!GoodsStatusEnum.UPPER.status().equals(data.getIsShow())) {
            throw new ServiceException(ResultCode.GOODS_NOT_EXIST);
        }
        return data;
    }
    /**
     * 检查并设置购物车商品数量
     * 根据购物类型，检查不同的 商品库存、认养产品库存
     * @param cartSkuVO 购物车商品对象
     * @param skuId     商品id
     * @param num       购买数量
     */
    private void checkSetGoodsQuantity(CartSkuVO cartSkuVO, String skuId, Integer num) {
        Integer enableStock = 0;
        if (cartSkuVO.getCartType().equals(CartTypeEnum.CART)) {
           enableStock = productService.getStock(skuId);
        } else if (cartSkuVO.getCartType().equals(CartTypeEnum.ADOPT)) {
            enableStock = adoptService.getStock(skuId);
        }else if (cartSkuVO.getCartType().equals(CartTypeEnum.BUY_NOW)) {
            enableStock = adoptService.getStock(skuId);
        }

        //如果商品的可用库存小于等于0或者小于用户购买的数量，则不允许购买
        if (enableStock <= 0 || enableStock < num) {
            throw new ServiceException(ResultCode.GOODS_SKU_QUANTITY_NOT_ENOUGH);
        }
        if (enableStock <= num) {
            cartSkuVO.setNum(enableStock);
        } else {
            cartSkuVO.setNum(num);
        }
        if (cartSkuVO.getGoodsSku() != null && !GoodsSalesModeEnum.WHOLESALE.name().equals(cartSkuVO.getGoodsSku().getSalesModel()) && cartSkuVO.getNum() > 99) {
            cartSkuVO.setNum(99);
        }
    }

    @Override
    public void shippingAddress(String shippingAddressId, String way) {
        //默认购物车
        CartTypeEnum cartTypeEnum = CartTypeEnum.CART;
        if (CharSequenceUtil.isNotEmpty(way)) {
            cartTypeEnum = CartTypeEnum.valueOf(way);
        }
        TradeDTO tradeDTO = this.readDTO(cartTypeEnum);
        UserAddress memberAddress = userAddressService.getById(Long.parseLong(shippingAddressId));
        tradeDTO.setUserAddress(memberAddress);
        this.resetTradeDTO(tradeDTO);
    }

    /**
     * 选择发票
     *
     * @param receiptVO 发票信息
     * @param way       购物车类型
     */
//    @Override
//    public void shippingReceipt(ReceiptVO receiptVO, String way) {
//        CartTypeEnum cartTypeEnum = CartTypeEnum.CART;
//        if (CharSequenceUtil.isNotEmpty(way)) {
//            cartTypeEnum = CartTypeEnum.valueOf(way);
//        }
//        TradeDTO tradeDTO = this.readDTO(cartTypeEnum);
//        tradeDTO.setNeedReceipt(true);
//        tradeDTO.setReceiptVO(receiptVO);
//        this.resetTradeDTO(tradeDTO);
//    }

    /**
     * 选择配送方式
     *
     * @param storeId        店铺id
     * @param deliveryMethod 配送方式
     * @param way            购物车类型
     */
    @Override
    public void shippingMethod(String storeId, String deliveryMethod, String way) {
        CartTypeEnum cartTypeEnum = CartTypeEnum.CART;
        if (CharSequenceUtil.isNotEmpty(way)) {
            cartTypeEnum = CartTypeEnum.valueOf(way);
        }
        TradeDTO tradeDTO = this.readDTO(cartTypeEnum);
        tradeDTO.setDeliveryMethod(DeliveryMethodEnum.valueOf(deliveryMethod).name());
//        for (CartVO cartVO : tradeDTO.getCartList()) {
//            cartVO.setDeliveryMethod(DeliveryMethodEnum.valueOf(deliveryMethod).name());
//            //cartVO.setShippingType(deliveryMethod);
//        }
        this.resetTradeDTO(tradeDTO);
    }

    /**
     * 获取购物车商品数量
     *
     * @param checked 是否选择
     * @return 购物车商品数量
     */
    @Override
    public Long getCartNum(Boolean checked) {
        //构建购物车
        TradeDTO tradeDTO = this.getAllTradeDTO();
        //过滤sku列表
        List<CartSkuVO> collect = tradeDTO.getSkuList().stream().filter(i -> Boolean.FALSE.equals(i.getInvalid())).collect(Collectors.toList());
        long count = 0L;
        if (!tradeDTO.getSkuList().isEmpty()) {
            if (checked != null) {
                count = collect.stream().filter(i -> i.getChecked().equals(checked)).count();
            } else {
                count = collect.size();
            }
        }
        return count;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void selectCoupon(String couponId, String way, boolean use) {
        // AuthUser currentUser = Objects.requireNonNull(UserContext.getCurrentUser());
        //获取购物车，然后重新写入优惠券
        CartTypeEnum cartTypeEnum = getCartType(way);
//
//        //积分商品不允许使用优惠券
//        if (cartTypeEnum.equals(CartTypeEnum.POINTS)) {
//            throw new ServiceException(ResultCode.SPECIAL_CANT_USE);
//        }
//
        TradeDTO tradeDTO = this.readDTO(cartTypeEnum);
//
//        MemberCouponSearchParams searchParams = new MemberCouponSearchParams();
//        searchParams.setMemberCouponStatus(MemberCouponStatusEnum.NEW.name());
//        searchParams.setMemberId(currentUser.getId());
//        searchParams.setId(couponId);
//        MemberCoupon memberCoupon = memberCouponService.getMemberCoupon(searchParams);
//        if (memberCoupon == null) {
//            throw new ServiceException(ResultCode.COUPON_EXPIRED);
//        }
//        //使用优惠券 与否
//        if (use) {
//            this.useCoupon(tradeDTO, memberCoupon, cartTypeEnum);
//        } else {
//            if (Boolean.TRUE.equals(memberCoupon.getPlatformFlag())) {
//                tradeDTO.setPlatformCoupon(null);
//            } else {
//                tradeDTO.getStoreCoupons().remove(memberCoupon.getStoreId());
//            }
//        }
        this.resetTradeDTO(tradeDTO);
    }


    @Override
    public Trade createTrade(TradeParams tradeParams) {
        //获取购物车
        CartTypeEnum cartTypeEnum = getCartType(tradeParams.getWay());
        TradeDTO tradeDTO = this.readDTO(cartTypeEnum);
        //设置基础属性
        tradeDTO.setClientType("小程序端");
        // tradeDTO.setStoreRemark(tradeParams.getRemark());
        tradeDTO.setMark(tradeParams.getMark());
        tradeDTO.setExtendOrderId(tradeParams.getParentOrderSn());
        //订单无收货地址校验
        if (tradeDTO.getUserAddress() == null) {
            throw new ServiceException(ResultCode.MEMBER_ADDRESS_NOT_EXIST);
        }
        //构建交易
        Trade trade = tradeBuilder.createTrade(tradeDTO);
        this.cleanChecked(this.readDTO(cartTypeEnum));
        return trade;
    }


    /**
     * 获取购物车类型
     *
     * @param way
     * @return
     */
    private CartTypeEnum getCartType(String way) {
        //默认购物车
        CartTypeEnum cartTypeEnum = CartTypeEnum.CART;
        if (CharSequenceUtil.isNotEmpty(way)) {
            try {
                cartTypeEnum = CartTypeEnum.valueOf(way);
            } catch (IllegalArgumentException e) {
                log.error("获取购物车类型出现错误：", e);
            }
        }
        return cartTypeEnum;
    }

    /**
     * 使用优惠券判定
     *
     * @param tradeDTO     交易对象
     * @param memberCoupon 会员优惠券
     * @param cartTypeEnum 购物车
     */
    private void useCoupon(TradeDTO tradeDTO, YxStoreCouponUser memberCoupon, CartTypeEnum cartTypeEnum) {

        //截取符合优惠券的商品
        List<CartSkuVO> cartSkuVOS = checkCoupon(memberCoupon, tradeDTO);

        //定义使用优惠券的信息商品信息
        Map<String, Double> skuPrice = new HashMap<>(1);


        //购物车价格
        double cartPrice = 0d;

        //循环符合优惠券的商品
//        for (CartSkuVO cartSkuVO : cartSkuVOS) {
//            if (Boolean.FALSE.equals(cartSkuVO.getChecked())) {
//                continue;
//            }
//            //有促销金额则用促销金额，否则用商品原价
//            if (cartSkuVO.getPromotionMap() != null && !cartSkuVO.getPromotionMap().isEmpty()) {
//                if (cartSkuVO.getPromotionMap().keySet().stream().anyMatch(i -> i.contains(PromotionTypeEnum.PINTUAN.name()) || i.contains(PromotionTypeEnum.SECKILL.name()))) {
//                    cartPrice = CurrencyUtil.add(cartPrice, CurrencyUtil.mul(cartSkuVO.getPurchasePrice(), cartSkuVO.getNum()));
//                    skuPrice.put(cartSkuVO.getGoodsSku().getId(), CurrencyUtil.mul(cartSkuVO.getPurchasePrice(), cartSkuVO.getNum()));
//                } else {
//                    cartPrice = CurrencyUtil.add(cartPrice, CurrencyUtil.mul(cartSkuVO.getGoodsSku().getPrice(), cartSkuVO.getNum()));
//                    skuPrice.put(cartSkuVO.getGoodsSku().getId(), CurrencyUtil.mul(cartSkuVO.getGoodsSku().getPrice(), cartSkuVO.getNum()));
//                }
//            } else {
//                cartPrice = CurrencyUtil.add(cartPrice, CurrencyUtil.mul(cartSkuVO.getGoodsSku().getPrice(), cartSkuVO.getNum()));
//                skuPrice.put(cartSkuVO.getGoodsSku().getId(), CurrencyUtil.mul(cartSkuVO.getGoodsSku().getPrice(), cartSkuVO.getNum()));
//            }
//        }


        //如果购物车金额大于消费门槛则使用
//        if (cartPrice >= memberCoupon.getConsumeThreshold()) {
//            //如果是平台优惠券
//            if (Boolean.TRUE.equals(memberCoupon.getPlatformFlag())) {
//                tradeDTO.setPlatformCoupon(new MemberCouponDTO(skuPrice, memberCoupon));
//            } else {
//                tradeDTO.getStoreCoupons().put(memberCoupon.getStoreId(), new MemberCouponDTO(skuPrice, memberCoupon));
//            }
//        }

    }

    /**
     * 获取可以使用优惠券的商品信息
     *
     * @param memberCoupon 用于计算优惠券结算详情
     * @param tradeDTO     购物车信息
     * @return 是否可以使用优惠券
     */
    private List<CartSkuVO> checkCoupon(YxStoreCouponUser memberCoupon, TradeDTO tradeDTO) {
        List<CartSkuVO> cartSkuVOS;
        //如果是店铺优惠券，判定的内容
        // memberCoupon.getPlatformFlag()
        if (Boolean.FALSE.equals(false)) {
            // cartSkuVOS = tradeDTO.getSkuList().stream().filter(i -> i.getStoreId().equals(memberCoupon.getStoreId())).collect(Collectors.toList());
            cartSkuVOS =  tradeDTO.getSkuList();
        }
        //否则为平台优惠券，筛选商品为全部商品
        else {
            cartSkuVOS = tradeDTO.getSkuList();
        }

        //当初购物车商品中是否存在符合优惠券条件的商品sku
//        if (memberCoupon.getScopeType().equals(PromotionsScopeTypeEnum.ALL.name())) {
//            return cartSkuVOS;
//        } else if (memberCoupon.getScopeType().equals(PromotionsScopeTypeEnum.PORTION_GOODS_CATEGORY.name())) {
//            //分类路径是否包含
//            return cartSkuVOS.stream().filter(i -> CharSequenceUtil.contains(memberCoupon.getScopeId(), i.getGoodsSku().getCategoryPath())).collect(Collectors.toList());
//        } else if (memberCoupon.getScopeType().equals(PromotionsScopeTypeEnum.PORTION_GOODS.name())) {
//            //范围关联ID是否包含
//            return cartSkuVOS.stream().filter(i -> CharSequenceUtil.contains(memberCoupon.getScopeId(), i.getGoodsSku().getId())).collect(Collectors.toList());
//        } else if (memberCoupon.getScopeType().equals(PromotionsScopeTypeEnum.PORTION_SHOP_CATEGORY.name())) {
//            //店铺分类路径是否包含
//            return cartSkuVOS.stream().filter(i -> CharSequenceUtil.contains(memberCoupon.getScopeId(), i.getGoodsSku().getStoreCategoryPath())).collect(Collectors.toList());
//        }
        return new ArrayList<>();
    }

    /**
     * 检测购物车
     *
     * @param cartTypeEnum 购物车枚举
     * @param cartSkuVO    SKUVO
     * @param skuId        SkuId
     * @param num          数量
     */
    private void checkCart(CartTypeEnum cartTypeEnum, CartSkuVO cartSkuVO, String skuId, Integer num) {

        this.checkSetGoodsQuantity(cartSkuVO, skuId, num);
//        //拼团判定
//        if (cartTypeEnum.equals(CartTypeEnum.PINTUAN)) {
//            //砍价判定
//            // checkPintuan(cartSkuVO);
//        } else if (cartTypeEnum.equals(CartTypeEnum.KANJIA)) {
//            //检测购物车的数量
//            // checkKanjia(cartSkuVO);
//        } else if (cartTypeEnum.equals(CartTypeEnum.POINTS)) {
//            //检测购物车的数量
//           // checkPoint(cartSkuVO);
//        }
    }


}
